// 数据接口
import axios from "axios"

import store from "../store"

import router from "../router"

import { Message } from "element-ui"

const instance = axios.create({
  timeout: 10 * 1000,
  baseURL: "/api",
})

instance.interceptors.request.use((config) => {
  const token = store.state.token
  token && (config.headers["X-Access-Token"] = token)
  // config.headers['X-Access-Token'] = store.state.token
  return config
})

instance.interceptors.response.use(
  (res) => {
    return res
  },
  (err) => {
    if (err.response) {
      if (err.response.data.message === "Token失效请重新登录") {
        Message.error("登录过期，请重新登录!!")
        sessionStorage.removeItem("X-Access-Token")
        window.sessionStorage.removeItem("userName")
        window.sessionStorage.removeItem("userId")
        router.replace({
          path: "/login",
        })
        return
      }
      switch (err.response.status) {
        case 500:
          console.log(err.response.data.message)
          Message.error("服务器错误")
          break
        case 404:
          Message.error("网络请求不存在")
          break
        default:
          return err
      }
    }
  }
)

export function request(config) {
  return instance(config)
}
